const getData = ()=>{
    const data = localStorage.getItem('initData') || '{}';
    return JSON.parse(data);
}

const setData = (data) =>{

    localStorage.setItem('initData',JSON.stringify(data))
}


const add = (key)=>{

    return (data, {newCount,code}:any={})=>{
        const preData = getData();
        preData[key].data.push(data);
        if(key == 'ORDER' && code){
            const {ORDER,...rest} = preData;

            const list:any = Object.values(rest).reduce((init:any,cur:any)=>{
                const {data:nData} = cur;
                init.push(...nData)
                return init
            },[] as any)
        
            const item = list.find(i=>{
                return i.code == code;
            })
            item.count = newCount;


        }
        setData(preData);


    }
}

const del = (key)=>{
    return (data)=>{
        const {code} =data;
        const preData = getData();
        const index = preData[key].data.findIndex(i=>i.code==code);
        preData[key].data.splice(index,1);
        setData(preData)
    }
}

const get = (key)=>{

    const data = getData();
    return data[key].data;
}



const getFucai = (code)=>{

    const data = getData();
    const {ORDER,...rest} = data;

    const list:any = Object.values(rest).reduce((init:any,cur:any)=>{
        const {data:nData} = cur;
        init.push(...nData)
        return init
    },[] as any)

    return list.find(i=>{
        return i.code == code;
    })



}




export default {
    add,
    del,
    getFucai,
    get
}